package br.com.ecomanda.managedbean;

import br.com.ecomanda.controller.EComandaController;
import br.com.ecomanda.controller.LoginController;
import br.com.ecomanda.exceptions.BusinessException;
import br.com.ecomanda.model.Funcionario;
import br.com.ecomanda.util.JSFUtil;

public class LoginBean {
		
	private LoginController loginController;
	
	private String username;
	
	private String password;
	
	private Funcionario funcionario;
	
	public LoginBean(){
		try {
			this.loginController = new LoginController();
		} catch (Exception e) {
			JSFUtil.addFacesErrorMessage( e.getMessage() );
			System.err.println( e.getMessage() );
		}
	}
	
	public String doLogin(){
		try {
			funcionario = loginController.login(username, password);			
			JSFUtil.storeOnSession("funcionario", funcionario);
			
			EComandaController parent = new EComandaController();
			JSFUtil.storeOnSession("parent", parent);
			
			return "home?faces-redirect=true";
		} catch (BusinessException e) {
			JSFUtil.addFacesErrorMessage( e.getMessage() );
			return "login";
		} catch (Exception e) {
			JSFUtil.addFacesErrorMessage( e.getMessage() );
			return "login";
		}
	}

	public String doLogout(){
		if( funcionario != null ){
			JSFUtil.removeFromSession("funcionario");
			JSFUtil.removeFromSession("parent");
			funcionario = null;
		}

		return "login?faces-redirect=true";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Funcionario getFuncionario() {
		return funcionario;
	}

	public void setFuncionario(Funcionario funcionario) {
		this.funcionario = funcionario;
	}

}
